from re import compile, search
import urllib
from threading import Thread

from Queue import Queue

from BeautifulSoup import BeautifulSoup

import dpcDBs as dbs


# Returns true if the login has succeeded
def validateLogin( resp ):
  c = resp.cookies
  return "USERNAME" in c and\
          "HASH" in c and\
          "PASSHASH" in c and\
          "EXPIRE" in c and\
          "PHPSESSID" in c and\
          "SESSION_KEY" in c



def parseChallengeEntries( user, resp ):
  soup = BeautifulSoup( resp.text )

  # Current entries
  entries = soup( 'a', {
      'class' : 'i',
      'href'  : compile( "comments" ) } )

  # Get the summaries and index of them
  currentScores = soup( 'td', {
    'class' : 'textsm2',
    'align' : None } )
  scoreInds = [range( ( i * 8 ) + i + 1, ( i * 8 ) + i + 8 ) for i in range( 0, len( currentScores ) / 9 )]



  # Loop through all the parsed entries
  newScore = []
  entryNames = []
  challengeIDs = []
  challengeNames = []


  for i, entry in enumerate( entries ):
    entryImageURL = str( entry.img['src'] )
    entryThumbURL = entryImageURL.replace( '/120/', '/800/' )
    entryID = int( search( r'(\d+)\.jpg', entryThumbURL ).group( 1 ) )
    entryURL = "http://www.dpchallenge.com/image.php?IMAGE_ID=" + str( entryID )
    entryName = entry.text

    challengeID = int( search( '/(\d+)/', entryImageURL ).group( 1 ) )
    challengeURL = 'http://www.dpchallenge.com/challenge_results.php?CHALLENGE_ID=' + str( challengeID )
    challengeName = str( soup( 'a', attrs = {
        'href': compile( r'challenge_vote_list.php\?CHALLENGE_ID=' + str( challengeID ) ) } )[0].text )

    # Add to the DB if appropriate

    challenge = dbs.challengeTable.selectBy( user = user, challengeID = challengeID )
    chExists = challenge.count()
    if chExists == 0:
      # Add to the DB
      entryImage = urllib.urlopen( entryThumbURL ).read()
      entryThumb = urllib.urlopen( entryImageURL ).read()

      challenge = dbs.challengeTable( 
        user = user,
        challengeName = challengeName,
        entryID = entryID,
        entryURL = entryURL,
        entryName = entryName,
        entryThumbURL = entryThumbURL,
        entryImageURL = entryImageURL,
        challengeID = challengeID,
        challengeURL = challengeURL,
        entryImage = entryImage,
        entryThumb = entryThumb )

    else:
      challenge = challenge.getOne()



    # ADD THE SCORES TO THE DB
    votes = int  ( currentScores[ scoreInds[i][0] ].text )
    views = int  ( currentScores[ scoreInds[i][1] ].text )
    score = float( currentScores[ scoreInds[i][2] ].text )
    comments = int  ( currentScores[ scoreInds[i][3] ].text )
    favourites = int  ( currentScores[ scoreInds[i][4] ].text )
    wishList = int  ( currentScores[ scoreInds[i][5] ].text )

    # Add the entry if necessary
    newEntry = dbs.voteTable.selectBy( 
      votes = votes,
      views = views,
      score = score,
      comments = comments,
      favourites = favourites,
      wishList = wishList ).count()

    if not newEntry:
      newScore.append( True )
      dbs.voteTable( 
        challenge = challenge,
        votes = votes,
        views = views,
        score = score,
        comments = comments,
        favourites = favourites,
        wishList = wishList )
    else:
      newScore.append( False )

    i += 1
    entryNames.append( entryName )
    challengeNames.append( challengeName )
    challengeIDs.append( challengeID )

  return ( challengeIDs, entryNames, challengeNames, newScore )

